<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"
    py:extends="'master.kid'">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" py:replace="''"/>
<?python
    import cherrypy

    if lat is None:
        lat = 55.31664304437719
    if lng is None:
        lng = 23.587646484375
    if level is None:
        level = 8
    if id is None:
        id = 0
?>
<title>Miestas</title>

    <link rel="alternate" title="Miestas" href="${'http://' + cherrypy.request.headers.get('Host', '') + '/feed/rss2_0'}" type="application/rss+xml"/>
    <link rel="alternate" title="Miesto komentarai" href="${'http://' + cherrypy.request.headers.get('Host', '') + '/feedcomments/rss2_0'}" type="application/rss+xml"/>
    <script py:attrs="src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=%s' % google_api_key"
            type="text/javascript"></script>
    <script src="/tg_js/MochiKit.js"></script>
    <script type="text/javascript">
    //<![CDATA[

    
    
    var g_active_marker = null;
    var g_map = null;
    var geocoder = new GClientGeocoder();


	function showAddress(address) {
	  geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	        alert(address + " not found");
	      } else {
	        g_map.setCenter(point, 13);
	      }
	    }
	  );
	}
	
    function msg_wait(message)
    {
        var flash = getElement('flash');
        flash.style.border = '1px solid #ff0';
        flash.style.backgroundColor = '#ffc';
        flash.style.padding = '2px';
        flash.style.margin = '0px 5px 0px 5px';
        flash.innerHTML = message + ' <img border="0" align="top" src="/static/images/palaukite.gif" alt="Palaukite"/>';
    }

    function msg_success(message)
    {
        var flash = getElement('flash');
        flash.style.border = '1px solid #0f0';
        flash.style.backgroundColor = '#cfc';
        flash.style.padding = '2px';
        flash.style.margin = '0px 5px 0px 5px';
        flash.innerHTML = message;
    }

    function msg_error(message)
    {
        var flash = getElement('flash');
        flash.style.border = '1px solid #f00';
        flash.style.backgroundColor = '#fcc';
        flash.style.padding = '2px';
        flash.style.margin = '0px 5px 0px 5px';
        flash.innerHTML = message;
    }

    function post_createNewMarker(results)
    {
        if (results['countryName'] != 'Lithuania')
        {
            msg_error('Neteisinga šalis. Prašom naudoti tik Lietuvą!');
        }
        else
        {
            marker = {id: null,
                title: '',
                latitude: results['lat'],
                longitude: results['lng'],
                modify: true,
                city: results['name'],
                street: '',
                number: '',
                description: '',
                rating: 0,
                rated: '',
                external_rating: '0',
                external_rated: false}
            createMarker(true, marker)
        }
    }

    function createMarkerYes(lat, lng) {
        replaceChildNodes('confirm', '');
        pre_createNewMarker(lat, lng);
    }

    function createMarkerNo() {
        replaceChildNodes('confirm', '');
    }

    function pre_createNewMarker(lat, lng)
    {
        var url = "${tg.url('reverse_geocode?')}";
        url += queryString({lat: lat, lng: lng});

        msg_wait('Prašome, palaukti. Siunčiama informacija apie vietovę.');

        var d = loadJSONDoc(url);
        d.addCallback(post_createNewMarker);
    }

    function selectMarker(marker)
        {
        g_active_marker = marker;

        if (marker.data.modify)
            {
            removeElementClass('MarkerForm', 'invisible');
            getElement('MarkerForm_Marker').value = marker.data.id;
            getElement('MarkerForm_Latitude').value = marker.getPoint().lat();
            getElement('MarkerForm_Longitude').value = marker.getPoint().lng();
            getElement('MarkerForm_Title').value = marker.data.title;
            getElement('MarkerForm_City').value = marker.data.city;
            getElement('MarkerForm_Street').value = marker.data.street;
            getElement('MarkerForm_Number').value = marker.data.number;
            getElement('MarkerForm_Description').value = marker.data.description;

            removeElementClass('DeleteForm', 'invisible');
            getElement('DeleteForm_Marker').value = marker.data.id;
            }
        else
            {
            addElementClass('MarkerForm', 'invisible');
            addElementClass('DeleteForm', 'invisible');
            }

        if (marker.data.id != null)
            {
            removeElementClass('AddCommentForm', 'invisible');
            getElement('AddCommentForm_Marker').value = marker.data.id;
            }
        else
            {
            addElementClass('AddCommentForm', 'invisible');
            }

        if (marker.data.id == null)
            {
            replaceChildNodes('comments', '');
            replaceChildNodes('rating', '');
            }

        // Rating buttons
        if ("${'miestas' in tg.identity.groups}" == "True")
            {
            if (marker.data.id != null)
                {
                button_negative = '';
                if (!marker.data.rated || marker.data.rated == 'True')
                    {
                    button_negative = INPUT({'type': 'button', 'value': '-'}, null);
                    connect(button_negative, 'onclick', partial(rate_internal, marker.data.id, -1));
                    }
                button_positive = '';
                if (!marker.data.rated || marker.data.rated == 'False')
                    {
                    button_positive = INPUT({'type': 'button', 'value': '+'}, null);
                    connect(button_positive, 'onclick', partial(rate_internal, marker.data.id,  1));
                    }
                replaceChildNodes('rating', SPAN(null, ['Įvertinkite:', button_negative, button_positive]));
                }
            else
                {
                replaceChildNodes('rating', SPAN(null, null));
                }
            }
        else
            {
            if (marker.data.id != null && !marker.data.external_rated)
                {
                button_negative = INPUT({'type': 'button', 'value': '-'}, null);
                connect(button_negative, 'onclick', partial(rate_external, marker.data.id, -1));
                button_positive = INPUT({'type': 'button', 'value': '+'}, null);
                connect(button_positive, 'onclick', partial(rate_external, marker.data.id,  1));
                replaceChildNodes('rating', SPAN(null, ['Įvertinkite:', button_negative, button_positive]));
                }
            else
                {
                replaceChildNodes('rating', SPAN(null, null));
                }
            }
        }

    function infoMarker(marker)
    {
        marker_info = DIV(null, [marker.data.title, BR(null, null),
                'Viešas įvertinimas: ' + marker.data.external_rating, BR(null, null),
                'Vidinis įvertinimas: ' + marker.data.rating, BR(null, null),
                marker.data.city + ', ' + marker.data.street + ' ' + marker.data.number, BR(null, null),
                marker.data.description]);
        marker.openInfoWindowHtml(marker_info.innerHTML);
    }

    function showMarkerComments(marker) {
        if (marker.data.id == null)
            return;

        var url = "${tg.url('get_comments?')}";
        url += queryString({id: marker.data.id});

        msg_wait('Prašome, palaukti. Siunčiami komentarai.');

        var d = loadJSONDoc(url);
        d.addCallback(showMarkerComments_complete);
    }

    function showMarkerComments_complete(results) {
        display_comments(results["comments"]);
        msg_success('Komentarai parsiųsti.');
    }

    function createMarker(select, marker_data)
        {
        var icon = new GIcon(G_DEFAULT_ICON);
        if (marker_data.rating == 0)
            icon.image = '/static/images/gray.png';
        else if (marker_data.rating < 0)
            icon.image = '/static/images/red.png';
        else
            icon.image = '/static/images/green.png';

        var marker = new GMarker(new GLatLng(marker_data.latitude, marker_data.longitude), {draggable: marker_data.modify, icon: icon});

        marker.data = marker_data;

        if (marker_data.modify)
            {
            GEvent.addListener(marker, "dragstart", function() {
              g_map.closeInfoWindow();
              });

            GEvent.addListener(marker, "dragend", function() {
                if (marker.data.id != null)
                {
                    var url = "${tg.url('update_marker_pos?')}";
                    url += queryString({id: marker.data.id,
                        lat: marker.getPoint().lat(),
                        lng: marker.getPoint().lng()});
                    msg_wait('Prašome, palaukti. Atnaujinama vietos pozicija.');
                    var d = loadJSONDoc(url);
                    d.addCallback(markerPositionUpdated);
                }
                else
                    markerPositionUpdated(null);
              });
            }

        g_map.addOverlay(marker);
        if (marker.data.id == ${id})
            {
            infoMarker(marker);
            showMarkerComments(marker);
            }
        if (select || marker.data.id == ${id})
            selectMarker(marker);
        msg_success('Nauja vieta sukurta.');
        }

    function markerPositionUpdated(result) {
        msg_success('Pozicija atnaujinta!');
    }

    function construct_url(position, level, marker)
    {
        var url = "http://" + "${cherrypy.request.headers.get('Host', '')}" + "${tg.url('/?')}";
        params = {lat: position.lat(),
            lng: position.lng(),
            level: level}
        if (marker != null)
            params['id'] = marker.data.id;

        url += queryString(params);
        return url
    }

    function load() {
        if (GBrowserIsCompatible()) {
            d = getViewportDimensions();
            getElement('map').style.height = d.h-180 + 'px';

            g_map = new GMap2(document.getElementById("map"), {});
            g_map.addControl(new GLargeMapControl());
            g_map.addControl(new GMapTypeControl());
            g_map.enableScrollWheelZoom();

            g_map.setCenter(new GLatLng("${lat}", "${lng}"), ${level});
            getElement('url').value = construct_url(g_map.getCenter(), g_map.getZoom(), null);

            GEvent.addListener(g_map, "click",

                    function(marker, point) {
                        if (marker)
                            {
                            if (marker.data != null)
                                {
                                selectMarker(marker);
                                infoMarker(marker);
                                showMarkerComments(marker);
                                getElement('url').value = construct_url(g_map.getCenter(), g_map.getZoom(), marker);
                                }
                            }
                        else
                            {
                            button_yes = INPUT({'type': 'button', 'value': 'Taip'}, null);
                            connect(button_yes, 'onclick', partial(createMarkerYes, point.lat(), point.lng()));
                            button_no = INPUT({'type': 'button', 'value': 'Ne'}, null);
                            connect(button_no, 'onclick', createMarkerNo);
                            replaceChildNodes('confirm', SPAN(null, ['Ar tikrai norite sukurti vietą?', button_yes, button_no]));
                            }
                        }
                );

            GEvent.addListener(g_map, "zoomend",
                    function(oldLevel, newLevel) {
                        getElement('url').value = construct_url(g_map.getCenter(), newLevel, g_active_marker);
                        }
                );

            GEvent.addListener(g_map, "moveend",
                    function() {
                        getElement('url').value = construct_url(g_map.getCenter(), g_map.getZoom(), g_active_marker);
                        }
                );

            GEvent.addListener(g_map, "dragend",
                    function() {
                        getElement('url').value = construct_url(g_map.getCenter(), g_map.getZoom(), g_active_marker);
                        }
                );

            msg_wait('Prašom, palaukti. Kraunami duomenys.');
            var d = loadJSONDoc("${tg.url('markerlist')}");
            d.addCallback(showMarkerList);
            }
        }

    function showMarkerList(result) {
        map(partial(createMarker, false), result["markers"]);
        msg_success('Duomenys užkrauti.');
    }

    function on_marker() {
        g_map.closeInfoWindow();
        msg_wait('Prašome, palaukti. Saugoma informacija apie vietą.')
    }

    function on_marker_complete(response) {
        results = eval("("+response+")");

        g_active_marker.data.id = results.id;
        g_active_marker.data.title = results.title;
        g_active_marker.data.city = results.city;
        g_active_marker.data.street = results.street;
        g_active_marker.data.number = results.number;
        g_active_marker.data.description = results.description;

        getElement('MarkerForm_Marker').value = results.id;
        getElement('AddCommentForm_Marker').value = results.id;
        getElement('DeleteForm_Marker').value = results.id;

        infoMarker(g_active_marker);
        selectMarker(g_active_marker);

        msg_success('Informacija apie vietą atnaujinta!');
    }

    function on_delete()
        {
        msg_wait('Prašome palaukti. Triname vietą.');
        }

    function on_delete_complete(response) {
        results = eval("("+response+")");

        g_map.closeInfoWindow();
        g_map.removeOverlay(g_active_marker);

        g_active_marker = null;

        addElementClass('MarkerForm', 'invisible');
        addElementClass('DeleteForm', 'invisible');
        addElementClass('AddCommentForm', 'invisible');
        replaceChildNodes('rating', '');
        replaceChildNodes('comments', '');
        msg_success('Vieta sėkmingai ištrinta.');
    }

    function on_comment() {
        msg_wait('Prašome, palaukti. Įrašomas komentaras.');
    }

    function display_one_comment(comment) {
        comment_fields = [A({'href': comment.homepage}, comment.author), BR(null, null),
                 SPAN(null, comment.datetime), BR(null, null),
                 SPAN(null, comment.text)]

        if ("${'miestas' in tg.identity.groups}" == "True")
        {
            button = INPUT({'type': 'button', 'value': 'Šalinti komentarą'}, null);
            connect(button, 'onclick', partial(delete_comment, comment.id));
            comment_fields.push(BR(null, null));
            comment_fields.push(button);
        }
        return DIV({'class': 'comment'}, comment_fields)
    }

    function display_comments(comments) {
        replaceChildNodes("comments", map(display_one_comment, comments));
    }

    function on_comment_complete(response) {
        results = eval("("+response+")");
        display_comments(results["comments"]);
        msg_success('Komentaras įrašytas.');
    }

    function rate_external(id, rating) {
        var url = "${tg.url('rate_external?')}";
        url += queryString({id: id, rating: rating});

        msg_wait('Prašome, palaukti. Siunčiamas įvertinimas.');

        var d = loadJSONDoc(url);
        d.addCallback(rate_external_complete);
    }

    function rate_external_complete(results) {
        g_active_marker.data.external_rating = results['rating']
        g_active_marker.data.external_rated = true;

        infoMarker(g_active_marker);
        selectMarker(g_active_marker);
        msg_success('Jūsų įvertinimas įrašytas.');
    }

    function rate_internal(id, rating) {
        var url = "${tg.url('rate_internal?')}";
        url += queryString({id: id, rating: rating});

        msg_wait('Prašome, palaukti. Siunčiamas įvertinimas.');

        var d = loadJSONDoc(url);
        d.addCallback(rate_internal_complete);
    }

    function rate_internal_complete(results) {
        g_active_marker.data.rating = results['rating'];
        g_active_marker.data.rated = results['rated'];
        if (results['rating'] == 0)
            g_active_marker.setImage('/static/images/gray.png');
        else if (results['rating'] < 0)
            g_active_marker.setImage('/static/images/red.png');
        else
            g_active_marker.setImage('/static/images/green.png');

        infoMarker(g_active_marker);
        selectMarker(g_active_marker);
        msg_success('Jūsų įvertinimas įrašytas.');
    }
    //]]>
    </script>

    <script py:if="'miestas' in tg.identity.groups" type="text/javascript">
    //<![CDATA[
    function delete_comment(id) {
        var url = "${tg.url('delete_comment?')}";
        url += queryString({id: id});

        msg_wait('Prašome, palaukite. Komentaras šalinamas.');
        var d = loadJSONDoc(url);
        d.addCallback(delete_comment_completed);
    }

    function delete_comment_completed(results) {
        msg_success('Komentaras ištrintas');
        display_comments(results["comments"]);
    }
    

    //]]>
    </script>

</head>
<body onload="load()" onunload="GUnload()">
    <div id="forms">
    	<div id="goto">
    		<input type="text" id="goto_city" onChange="showAddress(document.getElementById('goto_city').value)" />
    		<input type="submit" value="Go" onClick="showAddress(document.getElementById('goto_city').value)" />
		</div>
        <div id="location">       	
            <input class="textfield" type="text" id="url" />
        </div>
        <div id="confirm"/>
        <div id="rating"/>
        <span py:replace="marker_form.display(
               action='savemarkerform',
               before='on_marker()',
               form_attrs={'id': 'MarkerForm', 'class': 'tableform invisible'},
               on_complete='on_marker_complete(http_request.responseText)')">
        </span>
        <span py:replace="delete_form.display(
               action='delete_marker',
               before='on_delete()',
               form_attrs={'id': 'DeleteForm', 'class': 'tableform invisible'},
               on_complete='on_delete_complete(http_request.responseText)')">
        </span>
        <div id="comments"/>
        <span py:replace="add_comment_form.display(
               action='add_comment',
               before='on_comment()',
               form_attrs={'id': 'AddCommentForm', 'class': 'tableform invisible'},
               on_complete='on_comment_complete(http_request.responseText)')">
        </span>
    </div>


    <div id="map"></div>

</body>
</html>
